//
//  CZComposeVC.m
//  发微博（表情键盘，照片选择器）
//
//  Created by WONG on 16/4/4.
//  Copyright © 2016年 cheuhui. All rights reserved.
//

#import "CZComposeVC.h"
#import "CZPlaceholderTextView.h"
#import "PhotoSelectCVC.h"
#import "UIBarButtonItem+Extension.h"
#import "EmoticonPackage.h"


@interface CZComposeVC ()<UITextViewDelegate>

@property (nonatomic,strong) CZPlaceholderTextView *textView;
/**
 *  微博内容长度label
 */
@property (nonatomic,strong) UILabel *lengthTipLabel;
/**
 *  微博内容长度
 */
@property(nonatomic,assign)int statusLength;
/**
 *  照片选择器
 */
@property (nonatomic,strong) PhotoSelectCVC *photoSelectorCVC;
/**
 *  工具栏view   toolbar
 */
@property (nonatomic,strong) UIToolbar *toolbar;
/**
 *  照片选择器view的底部约束
 */
@property (nonatomic,strong) NSLayoutConstraint *photoSelectorViewBottonCon;


@end

@implementation CZComposeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.statusLength = 20;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self prepareUI];

    // 监听键盘的弹出和关闭
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
}
// 监听键盘的frame将要改变
- (void)willChangeFrame:(NSNotification *)notification {
    // 动画时间
    NSTimeInterval duration = [notification.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的最终位置
    CGRect endFrame = [notification.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    //NSLog(@"ScreenHeight - endFrame.origin.y) = %f",ScreenHeight - endFrame.origin.y);
        [self.toolbar mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.left.equalTo(self.view);
            make.height.equalTo(@44);
            make.bottom.equalTo(self.view.mas_bottom).offset(-(ScreenHeight - endFrame.origin.y));
        }];
    [UIView animateWithDuration:duration animations:^{
        [self.view layoutIfNeeded];
    }];
}
    

/**
 *  准备UI
 */
- (void)prepareUI {
    [self setupNAV];
    [self setupTextView];
    [self setupPhotoSelector];
    [self setupToolBar];
    [self setupLengthTipLabel];
}

// 设置导航栏
- (void)setupNAV {
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(close)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendStatus)];
    
    // 设置发送按钮不可用
    self.navigationItem.rightBarButtonItem.enabled = NO;
    
    [self setupTitle];
}
// 设置导航栏
- (void)setupTitle {
    NSString *pre = @"发微博";
    
    // 获取用户名称
    NSString *name = @"haha";
    
    if (name) {
        NSString *title = [NSString stringWithFormat:@"%@\n%@",pre,name];
        
        UILabel *label = [UILabel new];
        label.font = [UIFont systemFontOfSize:14];
        label.numberOfLines = 0;
        label.textAlignment = NSTextAlignmentCenter;
        
        // 属性文本
        // NSAttributedString: 不可变
        // NSMutableAttributedString: 可变的
        NSMutableAttributedString *attrText = [[NSMutableAttributedString alloc] initWithString:title];
        
        // 获取searchString 字符串在title里面的范围
        NSRange nameRange = [title rangeOfString:name];
        
        // 添加属性,修改 用户名称 的文字颜色
        // name: 要添加的属性名称 NSForegroundColorAttributeName: 文字颜色
        // value: 属性的值
        // NSRange: 修改属性的范围
        [attrText addAttribute:NSForegroundColorAttributeName value:[UIColor lightGrayColor] range:nameRange];
        
        // 修改name的大小
        [attrText addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:nameRange];
        
        // 设置属性文本
        label.attributedText = attrText;
        
        // 适应大小
        [label sizeToFit];
        
        self.navigationItem.titleView = label;
    }else {
        self.navigationItem.title = pre;
    }
    
    
}

// 设置textView
- (void)setupTextView {
    // 添加子控件
    [self.view addSubview:self.textView];
    
    // 填充父控件
    self.textView.frame = self.view.frame;
    
    _textView.delegate = self;
}

// 设置微博内容长度label
- (void)setupLengthTipLabel {
    // 添加子控件
    [self.view addSubview:self.lengthTipLabel];
    
    // 添加约束
    [self.lengthTipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.toolbar.mas_top).offset(-8);
        make.right.equalTo(self.view.mas_right).offset(-8);
    }];
    
}

// 设置照片选择器
- (void)setupPhotoSelector {
    [self.view addSubview:self.photoSelectorCVC.view];
    
    // 添加约束
    self.photoSelectorCVC.view.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 宽度填充父控件
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[psv]-0-|" options:0 metrics:nil views:@{@"psv": self.photoSelectorCVC.view}]];
    // 高度 = 父控件的 60%
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.photoSelectorCVC.view attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:ScreenHeight * 0.6]];
    // 底部与父控件的底部重合
    self.photoSelectorViewBottonCon = [NSLayoutConstraint constraintWithItem:self.photoSelectorCVC.view attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:ScreenHeight * 0.6];
    [self.view addConstraint:self.photoSelectorViewBottonCon];
}

// 设置toolBar
- (void)setupToolBar {
    [self.view addSubview:self.toolbar];
    
    // 添加约束
    [self.toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.left.bottom.equalTo(self.view);
        make.height.equalTo(@44);
    }];
}


#pragma mark - 导航栏按钮事件

- (void)close {
    // 关闭键盘
    [self.textView resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)sendStatus {

}

#pragma mark - toolbar的item被点击
- (void)picture {
    // 弹出照片选择器的view，键盘退下
    self.photoSelectorViewBottonCon.constant = 0;
    
    [UIView animateWithDuration:0.25 animations:^{
        // 根据新的内容更新约束
        [self.view layoutIfNeeded];
    }];
    // 键盘退下
    [self.view endEditing:YES];
}

- (void)trend {
    NSLog(@"#");
}

- (void)mention {
    NSLog(@"@");
}

- (void)emoticon {
    NSLog(@"表情键盘");
    
    EmoticonPackage *emo = [EmoticonPackage loadPackages];
    
    
    
}

- (void)add {
    NSLog(@"+");
}



#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    // 设置导航栏右边按钮的状态
    self.navigationItem.rightBarButtonItem.enabled = [self.textView hasText];
    // 计算微博内容剩余长度
//    int count = self.statusLength - [self.textView ];
    
}

#pragma mark - lazy load

- (CZPlaceholderTextView *)textView {
    if (!_textView) {
        _textView = [[CZPlaceholderTextView alloc] init];
        
        _textView.font = [UIFont systemFontOfSize:18];
        _textView.backgroundColor = [UIColor brownColor];
        _textView.alwaysBounceVertical = YES;
        _textView.placeholder = @"分享新鲜事";
        // 当拖动textView时，会让键盘退回去
        _textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    }
    return _textView;
}

- (UILabel *)lengthTipLabel {
    if (!_lengthTipLabel) {
        _lengthTipLabel = [[UILabel alloc] init];
        
        _lengthTipLabel.textColor = [UIColor lightGrayColor];
        _lengthTipLabel.font = [UIFont systemFontOfSize:12];
        _lengthTipLabel.text = [NSString stringWithFormat:@"%d",self.statusLength];
        [_lengthTipLabel sizeToFit];
    }
    return _lengthTipLabel;
}

- (PhotoSelectCVC *)photoSelectorCVC {
    if (!_photoSelectorCVC) {
        _photoSelectorCVC = [PhotoSelectCVC new];
        // 添加到当前控制器的子控制器
        [self addChildViewController:_photoSelectorCVC];
    }
    return _photoSelectorCVC;
}

- (UIToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [UIToolbar new];
        _toolbar.backgroundColor = [UIColor colorWithWhite:0.8 alpha:1];
        
        // 添加按钮
        NSArray *itemSettings = @[@{@"imageName": @"compose_toolbar_picture", @"action": @"picture"}, @{@"imageName": @"compose_trendbutton_background", @"action": @"trend"}, @{@"imageName": @"compose_mentionbutton_background", @"action": @"mention"}, @{@"imageName": @"compose_emoticonbutton_background", @"action": @"emoticon"}, @{@"imageName": @"compose_addbutton_background", @"action": @"add"}];
        // 存放 UIBarButtonItem 数组
        NSMutableArray<UIBarButtonItem *> *items = [NSMutableArray array];

        for (NSDictionary *dict in itemSettings) {
            // 获取图片名称
            NSString *imageName = dict[@"imageName"];
            // 获取方法名称
            NSString *ac = dict[@"action"];
        
            UIBarButtonItem *item = [UIBarButtonItem itemWithImageName:imageName target:self action:NSSelectorFromString(ac)];
            // 添加到toolbar
            [items addObject:item];
            // 添加弹簧
            [items addObject:[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]];
        }
        // 移除最后一个弹簧
        [items removeLastObject];
        _toolbar.items = items;
    }
    return _toolbar;
}

@end














